package com.chu.cloud.rabbit.listener;


import com.chu.cloud.dto.OrderDelayPay;
import com.chu.cloud.rabbit.dead.DelayMessagePayload;
import com.chu.cloud.rabbit.dead.DelayConstant;
import com.chu.cloud.service.OrderService;
import com.chu.cloud.util.JsonUtils;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: Tianshu.CHU
 * @Date: 2018/8/17 10:55
 * @Description:
 */
@RabbitListener(queues = DelayConstant.FanoutQueue.SECKILL_TIMEOUT_PAY)
@Component
@Slf4j
public class SeckillTimeOutPayReceive {

    @Autowired
    private Map<String, OrderService> orderServiceMap;

    @RabbitHandler
    public void process(@Payload DelayMessagePayload payload) {
        log.info("秒杀延迟队列收到消息:{}", payload);
        Stopwatch timer = Stopwatch.createStarted();
        try {
            OrderDelayPay orderDelayPay = JsonUtils.json2pojo(payload.getMessage(), OrderDelayPay.class);
            OrderService orderService = orderServiceMap.get(orderDelayPay.getOrderType());
            orderService.cancelOrder(orderDelayPay.getUserId(), orderDelayPay.getOrderNo());
        } catch (Exception e) {
            log.error("消费失败");
        }
        log.info("处理完订单取消操作, 耗时 {} 秒. ", timer.elapsed(TimeUnit.MILLISECONDS));
    }
}
